package org.example.aspect;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.constant.AuthConstants;
import org.example.domain.SysLog;
import org.example.model.SecurityUser;
import org.example.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect
@Slf4j
public class SysLogAspect {

    // 注入 SysLogService 用于保存日志
    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //切入点表达式
    public static final String POINT_CUT = "execution(* org.example.controller.*.*(..))";

    @Around(value = POINT_CUT)
    public Object logAround(ProceedingJoinPoint joinPoint) {
        Object result = null;
        // 获取请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        // 获取token值并解析出userId
        String au = request.getHeader(AuthConstants.AUTHORIZATION);
        String token = au.replaceFirst(AuthConstants.BEARER, "");
        String userJson = stringRedisTemplate.opsForValue().get(AuthConstants.LOGIN_TOKEN_PREFIX + token);
        SecurityUser securityUser = JSONObject.parseObject(userJson, SecurityUser.class);
        Long userId = securityUser.getUserId();

        // 获取请求地址
        String requestURI = request.getRequestURI();
        // 获取ip地址
        String remoteHost = request.getRemoteHost();
        // 获取请求参数
        Object[] args = joinPoint.getArgs();
        // 获取请求方法
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = method.toString();
        // 获取目标方法上的ApiOperation注解
        ApiOperation apiOperation = method.getDeclaredAnnotation(ApiOperation.class);
        // 判断该注解对象是否为空
        String operation = "";
        if (ObjectUtils.isNotNull( apiOperation)) {
            // 获取apiOperation注解的描述
            operation = apiOperation.value();
        }

        String finalArgs = "";
        // 判断参数类型
        if (ObjectUtils.isNotNull( args) && args.length!=0 && args[0] instanceof MultipartFile) {
            // 说明当前参数为文件对象
            finalArgs = "file";
        } else {
            // 将参数对象转换为json格式的字符串
            finalArgs = JSONObject.toJSONString( apiOperation);
        }

        // 记录开始时间
        long startTime = System.currentTimeMillis();
        try {
            // 执行方法
            result = joinPoint.proceed( args);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        // 记录结束时间
        long endTime = System.currentTimeMillis();

        //执行方法耗时
        long execTime = endTime - startTime;

        log.info( "请求时间：{},请求地址：{}，请求参数：{}，请求方法：{}，响应结果：{}，耗时：{}ms，方法描述：{}",
                new Date(), requestURI, finalArgs, methodName, result, execTime, operation);

        // 构建 SysLog 实体
        SysLog sysLog = SysLog.builder()
                .userId(userId) // 这里应根据实际情况设置用户ID
                .operation(operation)
                .method(methodName)
                .params(finalArgs)
                .time(execTime)
                .ip(remoteHost)
                .createDate(new Date())
                .build();

        // 保存日志到数据库
        sysLogService.save(sysLog);

        return result;
    }

}
